package hibernate;


import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

public class HibernateBaseDAO implements IBaseDao {
	
	public Logger logger = Logger.getLogger(this.getClass());
	protected Session session=null;

	// private Messages Messages=new Messages();

	
	private SessionFactory sessionFactory=HibernateSessionFactory.getSessionFactory();
	
	private static HibernateBaseDAO instance=null;
	private int DEFAULT_PAGENO=0;//默认分页起始页
	private int DEFAULT_PAGESIZE=20;//默认分页每页数据量
	/*
	 * 返回单个实例
	 */
	public static HibernateBaseDAO getInstance()
	{
		if(instance==null)
			instance=new HibernateBaseDAO();
		return instance;
	}
	/* (non-Javadoc)
	 * 
	*批量删除
	*clazz:要删除的持久化对象
	*id:对象的id数组
	 */
	public boolean batchDelete(Class clazz, Integer[] id) {
		// TODO Auto-generated method stub
		
		String strId = "";
		
		for (int i = 0; i < id.length; i++) {
			
			if (i > 0)
				
				strId += ", " + id[i];
			
			else
				
				strId = "" + id[i];
			
		}
		logger.debug("batchDelete(Class, long[])  id[]={" + strId + "}");
		
		for (int i = 0; i < id.length; i++) {
			
			this.delete(clazz, id[i]);
			
		}
		return true;

	}

	/* (non-Javadoc)
	 * 创建对象
	 */
	public void create(Object entity) {
		// TODO Auto-generated method stub		
		
		Transaction tr = null;
		
		boolean commitflag=false;
		
		try {
			session = this.getSession();
			
			tr = session.beginTransaction(); 
			
			session.save(entity);
			
			tr.commit();
			
			commitflag=true;
			
			session.flush();
			
			session.clear();
			
			// super.getHibernateTemplate().save(entity);
			
			logger.debug("保存" + entity.getClass().getName() + " 的实例到数据库成功！");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {			
			if(!commitflag)
			{
				try{
					
					if (tr != null)
						
						tr.rollback();
					
				}catch(Exception e1)
				{						
					logger.debug("事务",e1);					
				}
			}			
			this.closeSession(session);
		}
	}

	/* (non-Javadoc)
	 * 删除指定的持久化对象
	 * entity:持久化对象
	 */
	public boolean delete(Object entity) {
		// TODO Auto-generated method stub
		if(entity!=null)
			logger.debug("delete(Object) entity.class="
				+ entity.getClass().getName()); 		
		Transaction tr = null;
		
		boolean commitflag=false;
		
		try {

			session = this.getSession();
			
			tr = session.getTransaction();
			
			tr.begin();
			
			session.delete(entity);
			
			tr.commit();
			
			commitflag=true;
			
			session.flush();
			
			session.clear();
			

		} catch (Exception e) {
			
			if (tr != null)
				
				tr.rollback();
			logger.error("删除失败！");
			commitflag=false;
			
		} finally {			
			
			this.closeSession(session);
			return commitflag;
		}

	}

	/* (non-Javadoc)
	 * 删除对象
	 * clazz:对象类型
	 * id:对象的id
	 */
	public boolean delete(Class clazz, Integer id) {
		// TODO Auto-generated method stub
		
		logger.debug("ClassName=" + clazz.getName() + "  ,id=" + id);
		
		try {

			Object entity = this.getByPk(clazz, id);
			
			if (entity != null)
			{
				
				this.delete(entity);
				return true;
			}
			
			else
			{
				logger.debug(clazz.getName() + " 的关键字为 " + id + "  的对象不存在 ");
				return false;
			}

		} catch (Exception e) {
			
			logger.debug("  delete(Class, long)  excute is error  . Error="
					+ e.toString());	
			return false;
		}
	}

	/* (non-Javadoc)
	 * 删除所有对象
	 */
	public void deleteAll(Class clazz) {
		// TODO Auto-generated method stub
		
		logger.debug("deleteAll(Class) ClassName=" + clazz.getName());		
		
		Transaction tr = null;
		
		boolean commitflag=false;

		try {
						
			session = this.getSession();
			
			tr = session.beginTransaction();
			
			Query query = session.createQuery(" delete   from "
					+ clazz.getName());
			
			query.executeUpdate();
			
			tr.commit();
			
			commitflag=true;
			
			session.flush();
			
		} catch (Exception e) { 			
		
			logger.debug("delete class"+clazz.getName()+" error");
		} finally {
			
			if(!commitflag)
			{
				try
				{
					if (tr != null)
						
						tr.rollback();
					
				}catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			
			this.closeSession(session);
			
		}

	}

	/* (non-Javadoc)
	 * 批量删除不同类型的持久化对象
	 * entitie：持久化对象集合，可以是不同类型的对象集合
	 */
	public void deleteAll(Collection entities) {
		// TODO Auto-generated method stub		
		
		Transaction tr = null;
		
		boolean commitflag=false;
		
		try {
			
			session = this.getSession();
			
			tr = session.beginTransaction();
			
			Iterator ite = entities.iterator();
			

			while (ite.hasNext())
				
				session.delete(ite.next());
			
			// super.getHibernateTemplate().deleteAll(entities);
			tr.commit();
			
			commitflag=true;
			
			session.flush();
			

		} catch (Exception e) { 
			
			logger.debug("batch delete error");
			
		} finally {
			
			if(!commitflag)
			{
				try
				{
					if (tr != null)
						
						tr.rollback();
					
				}catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			
			this.closeSession(session);
			
		}
		
		

	}
	public boolean excuteHql(String strhql) {
		
		logger.debug("excuteSql(String) strsql=" + strhql);		
		
		Transaction tr = null;	
		
		try {
			
			session = this.getSession();
			
			tr = session.beginTransaction();
			
			Query query = session.createQuery(strhql);
			
			
			query.executeUpdate();
			
			tr.commit();			
			session.flush();
		} 
		catch (Exception e) {
			if (tr != null)				
				tr.rollback();
			e.printStackTrace();
			this.closeSession(session);
			return false;
		} 
		this.closeSession(session);
		return true;
	}
	/* (non-Javadoc)
	 * 执行无返回集的sql，如更新操作、删除操作
	 */
	public boolean excuteSql(String strsql) {
		// TODO Auto-generated method stub		
		logger.debug("excuteSql(String) strsql=" + strsql);		
		
		Transaction tr = null;	
		
		try {
			
			session = this.getSession();
			
			tr = session.beginTransaction();
			
			SQLQuery query = session.createSQLQuery(strsql);
			
			
			query.executeUpdate();
			
			tr.commit();			
			session.flush();
			
			

		} 
		catch (Exception e) {
			if (tr != null)				
				tr.rollback();
			e.printStackTrace();
			this.closeSession(session);
			return false;
		} 
		this.closeSession(session);
		return true;
	}

	/* (non-Javadoc)
	 * 查找对象，返回值为查找对象集合
	 * strhql：查询语句
	 */
	public List find(String strhql) {
		// TODO Auto-generated method stub
		
		List result = null;
		
		logger.debug("find(String) queryString=" + strhql);
		
		try {
			
			// result = super.getHibernateTemplate().find(queryString);
			
			session = this.getSession();
			
			Query query = session.createQuery(strhql);
			
			result = query.list();

		} catch (Exception e) {
			
			logger.debug("执行数据库中查询时失败,语句为：" + strhql, e);
			e.printStackTrace();
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result; 
	}

	/* (non-Javadoc)
	 * 使用参数查找对象，仅限于1个参数的使用
	 * strhql:查找语句
	 * para：查找参数
	 */
	public List find(String strhql, Object param) {
		// TODO Auto-generated method stub
		
		logger.debug("find(String, Object) queryString=" + strhql
				+ " ,param=" + param);

		List result = null;
		
		try {

			session = this.getSession();
			
			Query query = session.createQuery(strhql);
			
			query.setParameter(0, param);
			
			result = query.list();

			// result = super.getHibernateTemplate().find(queryString, param);

		} catch (Exception e) {
			
e.printStackTrace();
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
		 
	}

	/* (non-Javadoc)
	 * 根据名称绑定参数查找对象，仅限于1个参数
	 */
	public List findByNamedParam(String strhql, String name, Object param) {
		// TODO Auto-generated method stub


		logger.debug("findByNamedParam(String, String, Object) strhql="
				+ strhql + "name=" + name + " ,param=" + param);

		List result = null;
		
		try {
			session = this.getSession();
			
			Query query = session.createQuery(strhql);
			
			query.setParameter(name, param);
			
			result = query.list();

			// result =
			// super.getHibernateTemplate().findByNamedParam(queryString,
			// name, param);

		} catch (Exception e) {
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
		
	}

	/* (non-Javadoc)
	 * 根据字符串查找
	 */
	public List findBySql(String strsql) {
		// TODO Auto-generated method stub
		
		logger.debug("exceuteSQL(String) strsql=" + strsql);
		
		//System.out.println(strsql);
		
		List result=null;
		
		
		try {
			
			session = this.getSession(); 
			
			SQLQuery query = session.createSQLQuery(strsql);
			
			result=query.list();
			
			// super.getHibernateTemplate().update(entity);

		} catch (Exception e) { 
			
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
	}

	/* (non-Javadoc)
	 * 根据带参数绑定的字符串查找
	 * prams:参数列表
	 */
	public List findBySql(String strsql, List params) {
		// TODO Auto-generated method stub

		String paramnameArray=""; 
		 
		if(params!=null)
		{
			
			for (int i = 0; i < params.size(); i++) {
					
					if (i > 0)
						
						paramnameArray += " , " + params.get(i);
					
					else
						
						paramnameArray = ""+params.get(i);
					
			}
		
		}
		
		logger.debug("excuteSql(String, List) strsql="+strsql+" , List="+paramnameArray);
		
		System.out.println(strsql);
		
		List result =null;
		
		try { 
			
			session = this.getSession();
			
			
			SQLQuery query = session.createSQLQuery(strsql);
			
			if(params!=null)
			{
				for (int i = 0; i < params.size(); i++) {
										
					query.setParameter(i, params.get(i));
					
				} 
			}
			
			result  = query.list();

		} catch (Exception e) {
			
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;  
		
	}

	/* (non-Javadoc)
	 * 根据对象id查找
	 */
	public Object getByPk(Class clazz, int id) {
		// TODO Auto-generated method stub


		logger.debug("getByPk(Class, Integer) class=" + clazz.getName()
				+ " , ID=" + id);
		
		Object result = null;
		
		try {
			
			session = this.getSession();
			
			result = session.get(clazz, new Integer(id));			

		} catch (Exception e) {
			
			
		} finally {
			
			this.closeSession(session);
			
		}

		return result;
		
	}

	/* (non-Javadoc)
	 * 根据对象id查找
	 */
	public Object getByPk(Class clazz, Integer id) {
		// TODO Auto-generated method stub

		logger.debug("getByPk(Class, Long) Class=" + clazz.getName() + ",id="
				+ id);
		
		Object result = null;
		
		try {
			session = this.getSession();
			
			result = session.get(clazz, id);
			
			// (Object) super.getHibernateTemplate().get(clazz, id);

		} catch (Exception e) {
			logger.debug(e.toString());
			
		} finally {
			
			this.closeSession(session);
			
		}

		return result;
	}

	/* (non-Javadoc)
	 * 根据关键字查找
	 */
	public Object getByPk(Class clazz, String id) {
		// TODO Auto-generated method stub

		logger.debug("getByPk(Class, String) Class=" + clazz.getName() + ",id="
				+ id);
		
		Object result = null;
		
		try {

			session = this.getSession();
			
			result = session.get(clazz, id);
			
			// result = (Object) super.getHibernateTemplate().get(clazz, id);

		} catch (Exception e) {
			logger.debug(e.toString());
			
		} finally {
			
			this.closeSession(session);
			
		}

		return result;
		
	}

	/* (non-Javadoc)
	 * 获取session对象
	 */
	public Session getSession() {
		// TODO Auto-generated method stub
		
		return HibernateSessionFactory.getSession();
		
	}

	/* (non-Javadoc)
	 * 获取指定查找HQL字符串的记录总数
	 */
	public int getTotalCount(String strhql) {
		// TODO Auto-generated method stub

		logger.debug("getTotalCount() strhql=" + strhql);
		
		int result = 0;
		
		try {
			//对原查询字符串进行提取
			String strsql = this.getQueryTotalCountString(strhql);
			
			session = this.getSession();
			//使用提取后的字符串进行查找
			Query query = session.createQuery(strsql);
			
			List list = query.list();
			//获取结果集大小
			result = this.getNum(list);
			
		} catch (Exception e) {
			logger.debug(e.toString());
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
		
	}

	/* (non-Javadoc)
	 * 获取指定HQL查询字符串的记录总数，以obj作为条件进行查询，
	 */
	public int getTotalCount(String strhql, Object obj) {
		// TODO Auto-generated method stub
		
		logger.debug("getTotalCount(String,Object)  strhql=" + strhql
				+ "" + obj.getClass().getName());

		int result = 0;
		
		try {
			
			String strsql = this.getQueryTotalCountString(strhql);
			
			//System.out.println(strsql);
			
			logger.debug("strsql="+strsql);
			
			session = this.getSession();
			
			Query query = session.createQuery(strsql);
			
			List list = query.setProperties(obj).list(); 
				
			result = this.getNum(list);
			

		} catch (Exception e) {
			
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
	}

	/* (non-Javadoc)
	 * 获取指定查询HQL字符串记录总数，以params作为查询条件
	 */
	public int getTotalCount(String strhql, List params) {
		// TODO Auto-generated method stub
		
		String paramnameArray=""; 
		 
		if(params!=null)
		{
			
			for (int i = 0; i < params.size(); i++) {
					
					if (i > 0)
						
						paramnameArray += " , " + params.get(i);
					
					else
						
						paramnameArray = ""+params.get(i);
					
			}
		
		}
		
		logger.debug("getTotalCount(String, List) strhql="+strhql+" , List="+paramnameArray);
		
		
		int result = 0;
		
		try {
			
			String strquery = this.getQueryTotalCountString(strhql);
			
			//System.out.println(strsql);
			
			session = this.getSession();
			
			logger.debug("strquery=="+strquery);
			
			Query query = session.createQuery(strquery);
			
			if(params!=null)
			{
				for (int i = 0; i < params.size(); i++) {
										
					query.setParameter(i, params.get(i));
					
				} 
			}
			
			List list = query.list();

			result = this.getNum(list);
			

		} catch (Exception e) {
		
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;  
	}

	/* (non-Javadoc)
	 * 获取指定原生sql查询字符串的记录总数
	 */
	public int getTotalCountBySql(String strsql) {
		// TODO Auto-generated method stub
		
		logger.debug("getTotalCountBySql(String) strsql=" + strsql);
		
		int result = 0;
		
		try {
			
			strsql = this.getQueryTotalCountString(strsql);
			
			session = this.getSession(); 
			
			logger.debug("strsql=="+strsql);
			
			List list=session.createSQLQuery(strsql).list();
			 
			result = this.getNum(list);
			
		} catch (Exception e) {
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
		 
	}

	/* (non-Javadoc)
	 * 获取指定原生sql字符串查找记录总数，params为查询条件
	 */
	public int getTotalCountBySql(String strsql, List params) {
		// TODO Auto-generated method stub
		
		String paramnameArray=""; 
		 
		if(params!=null)
		{
			
			for (int i = 0; i < params.size(); i++) {
					
					if (i > 0)
						
						paramnameArray += " , " + params.get(i);
					
					else
						
						paramnameArray = ""+params.get(i);
					
			}
		
		}
		
		logger.debug("getTotalCountBySql(String, List) strsql="+strsql+" , List="+paramnameArray);
		
		
		int result = 0;
		
		try {
			
			strsql = this.getQueryTotalCountString(strsql);
			
			logger.debug("strsql=="+strsql);
			
			session = this.getSession();
			
			SQLQuery query = session.createSQLQuery(strsql);
			
			if(params!=null)
			{
				for (int i = 0; i < params.size(); i++) {
										
					query.setParameter(i, params.get(i));
					
				} 
			}
			
			List list = query.list();

			result = this.getNum(list);
			

		} catch (Exception e) {
			
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
		 
	}

	/* (non-Javadoc)
	 * 使用hql查询字符串查找并加载持久化对象
	 */
	public List loadAll(String strhql) {
		// TODO Auto-generated method stub
		return this.find(strhql);
	}

	/* (non-Javadoc)
	 * 根据关键字加载对象
	 */
	public Object loadByPk(Class clazz, String keyName, Object keyValue) {
		// TODO Auto-generated method stub
		
		Object result = null;
		
		String query = "from " + clazz.getName() + "  where " + keyName + "=? ";
		
		logger.debug("loadByPk(Class, String, Object) queryString=" + query
				+ "  ,keyValue=" + keyValue);
		
		try {

			session = this.getSession();
		
			result = session.createCriteria(clazz).add(
					Restrictions.eq(keyName, keyValue)).list();
			

		} catch (Exception e) {
			
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;		
		
	}

	/* (non-Javadoc)
	 * 使用hql进行分页查找，以第0页为起始页
	 */
	public List query(int pageNo, int pageSize, String strhql) {
		// TODO Auto-generated method stub

		logger.debug("query(int, int, String) pageNo=" + pageNo + ",pageSize="
				+ pageSize + " ,strhql=" + strhql);

		List result = null;
		
		try {
			session = this.getSession();
			
			Query query = session.createQuery(strhql);
			//System.out.println(queryString);
			
			if (pageNo > 0 ) {
				
				query.setFirstResult((pageNo-1 ) * pageSize);
				
			
			}
			else
				query.setFirstResult(this.DEFAULT_PAGENO);
			if(pageSize>0)
				query.setMaxResults(pageSize);
			else
				query.setMaxResults(this.DEFAULT_PAGESIZE);
			result = query.list();
			
			//System.out.println()
		} catch (Exception e) {
		
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
	}

	/* (non-Javadoc)
	 * 分页查找
	 * strhql：查询hql语句
	 * obj：条件查询对象
	 */
	public List query(int pageNo, int pageSize, String strhql, Object obj) {
		// TODO Auto-generated method stub

		logger.debug("query(int, int, String, Object) pageNo=" + pageNo
				+ ",pageSize=" + pageSize + "strhql="+strhql+"  ,obj"
				+ obj.getClass().getName());
		
		List result = null;
		
		try {
			
			session = this.getSession();
			
			Query query = session.createQuery(strhql);
			
			query.setProperties(obj);
			
			if (pageNo > 0 && pageSize > 0) {
				
				query.setFirstResult((pageNo ) * pageSize);
				
				query.setMaxResults(pageSize);
				
			}
			
			result = query.list();
			
		} catch (Exception e) {
			
		
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result;
		
	}

	/* (non-Javadoc)
	 * 分页查询
	 * strhql:查询hql语句
	 * params:条件查询
	 */
	public List query(int pageNo, int pageSize, String strhql, List params) {
		// TODO Auto-generated method stub

		logger.debug("query(int, int, String, Object) pageNo=" + pageNo + ",pageSize=" + pageSize + ",strhql="+strhql);		
		
		String paramnameArray="";
		
		if(params!=null)
		{
			
			for (int i = 0; i < params.size(); i++) {
					
					if (i > 0)
						
						paramnameArray += " , " + params.get(i);
					
					else
						
						paramnameArray = ""+params.get(i);
					
			}
		
		}
		
		logger.debug("params="+params);
		
		List result = null;
		
		try {
			
			session = this.getSession();
			
			Query query = session.createQuery(strhql);
			
			if(params!=null)
			{
				for (int i = 0; i < params.size(); i++) {
										
					query.setParameter(i, params.get(i));
					
				} 
			}
			
			if (pageNo > 0 && pageSize > 0) {
				
				query.setFirstResult((pageNo - 1) * pageSize);
				
				query.setMaxResults(pageSize);
				query.setCacheable(false);//禁用缓存
				
			}
			
			result = query.list();
			
		} catch (Exception e) {
			
		
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result; 
		
	}

	private static List convertList(ResultSet rs) throws SQLException { 

		List list = new ArrayList(); 

		ResultSetMetaData md = rs.getMetaData(); 

		int columnCount = md.getColumnCount(); //Map rowData; 

		while (rs.next()) { //rowData = new HashMap(columnCount); 

		Map rowData = new HashMap(); 
		Object[] obj=new Object[columnCount];

		for (int i = 1; i <= columnCount; i++) { 

			rowData.put(md.getColumnName(i), rs.getObject(i)); 
			obj[i-1]=rs.getObject(i);
		} 

		list.add(obj); 

		} 
		return list; 

	}
	/* (non-Javadoc)
	 * 使用sql语句分页查询
	 */
	public List queryBySql(int pageNo, int pageSize, String strsql) {
		// TODO Auto-generated method stub


		logger.debug("query(int, int, String) pageNo=" + pageNo + ",pageSize="
				+ pageSize + " ,strsql=" + strsql);

		List result = null;
		
		try {
			
			session = this.getSession();	
			
			Query query = session.createSQLQuery(strsql);
			
			if (pageNo > 0 && pageSize > 0) {
				
				query.setFirstResult((pageNo - 1) * pageSize);				
			}
			if(pageSize>0)
				query.setMaxResults(pageSize);
			result = query.list();				
			query.setCacheable(false);//取消缓存
			//sessionFactory.close();
			//sessionFactory.close();
		} catch (Exception e) {
			
			System.out.println(e.toString());
			
		} finally {
			
			this.closeSession(session);
			
		}
		
		return result; 
		
	}

	/* (non-Javadoc)
	 * 使用sql语句分页查询
	 */
	public List queryBySql(int pageNo, int pageSize, String strsql, List params) {
		// TODO Auto-generated method stub

		logger.debug("query(int, int, String, Object) pageNo=" + pageNo + ",pageSize=" + pageSize + " , strsql="+strsql);		
		
		String paramnameArray="";
		
		if(params!=null)
		{
			
			for (int i = 0; i < params.size(); i++) {
					
					if (i > 0)
						
						paramnameArray += " , " + params.get(i);
					
					else
						
						paramnameArray = ""+params.get(i);
					
			}
		
		}
		
		logger.debug("params="+params);
		
		List result = null;
		
		try {
			
			session = this.getSession();
			
			SQLQuery query = session.createSQLQuery(strsql);
			
			if(params!=null)
			{
				for (int i = 0; i < params.size(); i++) {
										
					query.setParameter(i, params.get(i));
					
				} 
			}
			
			if (pageNo > 0 && pageSize > 0) {
				
				query.setFirstResult((pageNo - 1) * pageSize);
				
				query.setMaxResults(pageSize);
				query.setCacheable(false);//禁止用缓存
				
			}
			
			result = query.list();
			
		} catch (Exception e) {
			
			
		} finally {
			
			this.closeSession(session);
			
		}
		return result; 
		
	}

	/* (non-Javadoc)
	 * @see zhenjw.hibernate.dao.IBaseDao#update(java.lang.Object)
	 */
	public void update(Object entity) {
		// TODO Auto-generated method stub
		
		logger.debug("update(Object) entity.class="
				+ entity.getClass().getName());
		
		Transaction tr = null;
		
		try {
			session = this.getSession();
			
			tr = session.beginTransaction();
			
			session.update(entity);
			
			tr.commit();
			
			session.flush();
			
			session.clear();
			
			// super.getHibernateTemplate().update(entity);

		} catch (Exception e) {
			e.printStackTrace();
			if (tr != null)
				
				tr.rollback();
			
			
		} finally {
			
			this.closeSession(session);
			
		}

	}
	
	/**
	 * 功能：关闭session
	 * @param session
	 */
	protected void closeSession(Session session) {

		if (session != null && session.isOpen())
			
			session.close();
		
		session = null;
		
	}
	
	/**
	 * 功能：得到查询记录总数的语句（包含sql与hql）
	 * @param queryString
	 * @return
	 */
	private String getQueryTotalCountString(String queryString) {

		int form_index = queryString.indexOf("from ");
		
		int orderby_index = queryString.indexOf(" order by ");
		
		if (form_index < 0) {
			
			
		}
		
		String strsql = " select count(*) ";
		
		if (orderby_index > -1) {
			
			strsql = strsql + queryString.substring(form_index, orderby_index);

		} else {
			
			strsql = strsql + queryString.substring(form_index);
		}

		return strsql;
	}
	
	/**
	 * 功能：得到记录数的方法
	 * @param list
	 * @return
	 */
	protected int getNum(List list)
	{
		
		int result=0;
		
		if (list != null || list.size() > 0) 
			
			result = Integer.parseInt(list.get(0).toString());
		
		 return result;
	}

	public void delete(List objects) {
		// TODO Auto-generated method stub
		 if(objects==null)
   		 	return;
		 Transaction tx=null;
	   	 try
	   	 {
		    	 session=this.getSession();
		 		 tx=session.beginTransaction();
		    	 for(int i=0;i<objects.size();i++)
		    	 {
		    		 session.delete(objects.get(i));
		    	 }
		    	 tx.commit();
		    	 //session.clear();
			     this.closeSession(session);	    	 
	   	 }
	   	 catch(Exception e)
	   	 {	   		 
	   		 if(tx!=null)
	   			 tx.rollback();
	   		 e.printStackTrace();
	   	 }
	}

	public Object getById(String className, Integer id) {
		// TODO Auto-generated method stub
		session=this.getSession();
   	 	Object temp=session.get(className, id);//注意使用get方法和load方法的区别
   	 	this.closeSession(session);
   	 	return temp;
	}

	public List getList(String className) {
		// TODO Auto-generated method stub
		session=this.getSession();
   	 	Query query=null;
   	 	query=session.createQuery("from "+className);
   	 	List list=query.list();
   	 	this.closeSession(session);
   	 	return list;
	}

	public void save(Object object) {
		// TODO Auto-generated method stub
		if(object==null)
   		 return;	
		Transaction tx=null;
	   	try
	   	{
	   		session=this.getSession();
	   		tx=session.beginTransaction();
	   	    session.saveOrUpdate(object);
	   	    tx.commit();
	   	    this.closeSession(session);				
	   	}
	   	catch(Exception e)
	   	{	   		
	   		if(tx!=null)
	   			tx.rollback();
	   		e.printStackTrace();
	   	}
	}

	public void save(List objects) {
		// TODO Auto-generated method stub
		if(objects==null)
   		 return;
		Transaction tx=null;
   	 	try
    	{
    		session=this.getSession();
    		tx=session.beginTransaction();
    	    for(int i=0;i<objects.size();i++)
    	    {
    	    	session.saveOrUpdate(objects.get(i));
    	    }
    	    tx.commit();
    	    this.closeSession(session);
			
    	}
    	catch(Exception e)
    	{    		
    		if(tx!=null)
    			tx.rollback();
    		e.printStackTrace();
    	}
	}
	
	public boolean saveOrupdate(Object entity) {
		// TODO Auto-generated method stub
		//By:Silence
		logger.debug("update(Object) entity.class="
				+ entity.getClass().getName());
		
		
		Transaction tr = null;
		
		try {
			session = this.getSession();
			
			tr = session.beginTransaction();
			
			session.saveOrUpdate(entity);
			
			tr.commit();
			
			session.flush();
			
			//session.clear();
			this.closeSession(session);
			// super.getHibernateTemplate().update(entity);

		} catch (Exception e) {
			e.printStackTrace();
			if (tr != null)
				
				tr.rollback();
			this.closeSession(session);
			return false;		
		} 
		return true;
	}	
	

}